package org.merka.cryptochat.controller;

import javax.servlet.http.HttpServletRequest;

import org.merka.cryptochat.dao.IUserManager;
import org.merka.cryptochat.entity.ChatUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes(IndexController.USERS)
//@RequestMapping(value = {"/"})
public class IndexController
{
	
	private static transient Logger logger = LoggerFactory.getLogger(IndexController.class);
	public static final String USERS = "users";
	public static final String CHAT_VIEW = "chatView";
	public static final String CHAT_USER = "chatUser";
	
	public static String INDEX_VIEW = "index";
	
	public IndexController()
	{
		
	}
	
	@Autowired
	private IUserManager userManager;
	
	public IUserManager getUserManager()
	{
		return userManager;
	}

	public void setUserManager(IUserManager userManager)
	{
		this.userManager = userManager;
	}

	@ModelAttribute(CHAT_USER)
	public ChatUser chatUser()
	{
		return new ChatUser();
	}
	
	@RequestMapping("/webgl")
	public String webGLDemoView()
	{
		return "webGLdemoView";
	}
	
	@RequestMapping("/enter")
	public String enterChat(@RequestParam(value = "username", required = true) String username,
			@ModelAttribute(CHAT_USER) ChatUser chatUser)
	{
		logger.info("\n\n\nChatUser username: " + chatUser.getUsername());
		logger.info("Public Key: " + chatUser.getChatPublicKey().getPublicKey() + "\n\n\n");
		getUserManager().addChatUser(chatUser);
		return CHAT_VIEW;
	}
	
	@RequestMapping(value = {"/", "/index"})
	public String index(HttpServletRequest request)
	{
		logger.info("index");
		return INDEX_VIEW;
	}

	@MessageMapping(value = "/ws")
	@SendTo(value = "/ws")
	public String onMessage(String textMessage)
	{
		logger.info("onMessage: '" + textMessage + "'");
		return "OK";
	}
}
